package com.pw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pw.gmall.realtime.app.BaseApp;
import com.pw.gmall.realtime.common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author: linux_future
 * @since: 2022/3/19
 **/
public class DwdUserJumpDetailApp extends BaseApp {
    public static void main(String[] args) {
        new DwdUserJumpDetailApp().init(2004,1,"dwdUserJump","dwdUserJump", Constant.TOPIC_DWD_PAGE_LOG);
    }

    @Override
    protected void handler(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //水印
        WatermarkStrategy<JSONObject> wms = WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((obj, ts) -> obj.getLong("ts"));

        stream =
                env.fromElements(
                        "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000}",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"home\"},\"ts\":39999} ",
                        "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                                "\"detail\"},\"ts\":50000} "
                );


        KeyedStream<JSONObject, String> dataStream = stream.map(JSON::parseObject).assignTimestampsAndWatermarks(wms)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"));

        //定义模式
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("start")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        //判断是否为空
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return lastPageId == null || lastPageId.length() == 0;
                    }
                }).next("next")
                .where(new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        //下一个页面
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return lastPageId != null || lastPageId.length() > 0;
                    }
                }).within(Time.seconds(5));

        //模式与流绑定
        PatternStream<JSONObject> ps = CEP.pattern(dataStream, pattern);

        //模式匹配数据处理
        OutputTag<JSONObject> outputTagJump = new OutputTag<JSONObject>("jump") {
        };
        SingleOutputStreamOperator<JSONObject> mainStream = ps.select(outputTagJump, new PatternTimeoutFunction<JSONObject, JSONObject>() {
            @Override
            public JSONObject timeout(Map<String, List<JSONObject>> map, long timeoutTimestamp) throws Exception {
                System.out.println("超时数据。。。。。");
                return map.get("start").get(0);
            }
        }, new PatternSelectFunction<JSONObject, JSONObject>() {
            @Override
            public JSONObject select(Map<String, List<JSONObject>> map) throws Exception {
                System.out.println("匹配数据。。"+map.toString());
                return null;
            }
        });

        mainStream.getSideOutput(outputTagJump).print("超时数据：");
        mainStream.print("主流数据：");

    }
}
